package com.note.backend.service.impl.user.account;

import com.note.backend.pojo.User;
import com.note.backend.service.impl.utils.UserDetailsImpl;
import com.note.backend.service.user.account.GetInfoService;
import com.note.backend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class GetInfoServiceImpl implements GetInfoService {
    @Override
    public Result getInfo() {
        //如果授权成功 则从上下文中将User信息提取出来
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication == null || !authentication.isAuthenticated()) {
                return Result.error("用户未登录");
            }

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            User user = userDetails.getUser();

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("photo", user.getPhoto());

            log.info("用户信息获取成功: {}", user.getUsername());
            return Result.success(userInfo);
        } catch (ClassCastException e) {
            log.error("用户信息解析失败: {}", e.getMessage());
            return Result.error("用户身份信息异常");
        } catch (Exception e) {
            log.error("系统异常: {}", e.getMessage());
            return Result.error("系统繁忙，请稍后重试");
        }
    }
}